package com.bawei.lib_common.livedata_eventbus

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer

/**
 * @author yaotianxue
 * @description
 * @date 2025/5/28
 */
object LiveDataBus {
    // 存储所有事件的 Map，key 为事件类型，value 为对应的 LiveData
    private val events = mutableMapOf<String, EventLiveData<*>>()
//    fun <T> with(eventName: String): MutableLiveData<T> {
//        if (!events.containsKey(eventName)){
//            events[eventName] = EventLiveData<T>()
//        }
//        return  events[eventName] as MutableLiveData<T>
//    }
    // 获取或创建 LiveData
    @Suppress("UNCHECKED_CAST")
    private fun <T> getLiveData(eventType: String): EventLiveData<T> {
        return events.getOrPut(eventType) { EventLiveData<T>() } as EventLiveData<T>
    }
    // 发送粘性事件
    fun <T> postSticky(eventType: String, data: T) {
        getLiveData<T>(eventType).postSticky(data)
    }

    // 发送非粘性事件
    fun <T> post(eventType: String, data: T) {
        getLiveData<T>(eventType).post(data)
    }

    // 观察粘性事件
    fun <T> observeSticky(
        owner: LifecycleOwner,
        eventType: String,
        observer: Observer<T>
    ) {
        getLiveData<T>(eventType).observe(owner, observer, true)
    }



    // 观察非粘性事件
    fun <T> observe(
        owner: LifecycleOwner,
        eventType: String,
        observer: Observer<T>
    ) {
        getLiveData<T>(eventType).observe(owner, observer,false)
    }





    // 自定义 LiveData
    private class EventLiveData<T> : MutableLiveData<Event<T>>() {
        // 发送粘性事件
        fun postSticky(data: T) {
            postValue(Event.Sticky(data))
        }

        // 发送非粘性事件
        fun post(data: T) {
            postValue(Event.Normal(data))
        }

        // 观察粘性和非粘性事件
        fun observe(owner: LifecycleOwner, observer: Observer<T>,isSticky:Boolean) {
            super.observe(owner, EventObserver(observer, isSticky))
        }

//        // 观察非粘性事件
//        fun observe(owner: LifecycleOwner, observer: Observer<T>) {
//            super.observe(owner, EventObserver(observer, isSticky = false))
//        }
    }
}